package com.siyoumi.app.modules.act.interceptor;

import com.siyoumi.app.entity.ActSet;
import com.siyoumi.app.modules.act.service.SvcActSet;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.interceptor.InterceptorBase;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//活动api
@Slf4j
public class ActApiInterceptor
        extends InterceptorBase
        implements HandlerInterceptor {
    /**
     * 执行前
     *
     * @return boolean
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("BEGIN");

        InputData inputData = InputData.fromRequest();
        String actId = inputData.input("act_id");

        if (XStr.isNullOrEmpty(actId)) {
            return returnErr(response, EnumSys.MISS_VAL.getR("miss act_id"));
        }

        ActSet entityAct = SvcActSet.getBean().getEntity(actId);
        if (entityAct == null) {
            return returnErr(response, EnumSys.ERR_VAL.getR("act_id error"));
        }
        if (!entityAct.getAset_x_id().equals(XHttpContext.getX())) {
            return returnErr(response, EnumSys.ERR_VAL.getR("act_id error[x]"));
        }

        String urlPath = XHttpContext.getUrlPath();
        String[] urlPathArr = urlPath.split("/");
        String methodName = urlPathArr[urlPathArr.length - 1];
        log.info("url_path: {}", urlPath);
        log.info("method_name: {}", methodName);

        Boolean vaildPass = false; //是否验证活动有效期
        if (methodName.equals("init")) {
            vaildPass = true;
        }
        XReturn r = entityAct.valid(vaildPass);
        if (r.err()) {
            return returnErr(response, r);
        }


        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("END");
    }
}
